package com.example.securitytest.service.impl;

import com.example.securitytest.dao.MyUserDAO;
import com.example.securitytest.dataobject.MyUser;
import com.example.securitytest.dataobject.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 自行实现Spring Security的登录逻辑
 */
@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private MyUserDAO myUserDAO;

	/**
	 * 取出用户
	 *
	 * @param username 用户名
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		MyUser myUser = myUserDAO.getByUsername(username);
		if (myUser == null) {
			throw new UsernameNotFoundException("找不到用户！");
		}
		// 组装权限
		Set<GrantedAuthority> authorities = new HashSet<>();
		Set<Permission> permissions = myUser.getPermissions();
		for (Permission permission : permissions) {
			authorities.add(new SimpleGrantedAuthority(permission.getName()));
		}
		return new User(myUser.getUsername(), myUser.getPassword(), authorities);
	}

}